package com.boss.salary.service.impl;

import com.boss.common.entity.PageDTO;
import com.boss.common.entity.WfActionDTO;
import com.boss.common.enums.ActionTypeEnum;
import com.boss.common.enums.StatusCodeEnum;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.*;
import com.boss.salary.entity.AgencyInfo;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.service.IFinancialAuditService;
import com.boss.salary.vo.FinancialAuditVO;
import com.boss.salary.workflow.service.ISalaryWorkFlowService;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FinancialAuditServiceImpl implements IFinancialAuditService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(FinancialAuditServiceImpl.class);

    @Autowired
    private IFinancialAuditDao iFinancialAuditDao;

    @Autowired
    private IAgencyVerifyDao iAgencyVerifyDao;
    @Autowired
    private IAgencyInfoDao agencyInfoDao;
    @Autowired
    private ISalaryWorkFlowService iSalaryWorkFlowService;
    @Autowired
    private IPersonExtSubmitDao personExtSubmitDao;
    @Autowired
    private ISalaryMonthEndSubmitDao salaryMonthEndSubmitDao;
    @Autowired
    private IPayMentLockDao iPayMentLockDao;

    @Autowired
    private ICommonService commonService;

    @Override
    public PageDTO<FinancialAuditVO> queryFinancialAuditPage(UserDTO userDto, PaginationDTO paginationDTO,
                                                             Map<String, Object> queryParam,
                                                             List<String> childrenId) throws AppRuntimeException {

        // 查询工作流待办数量

       // List<String> bizKeys = new ArrayList<>();
       // List<HashMap<String, String>> bizKeys=new ArrayList<>();
        List<String> bizKeys=new ArrayList<>();
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(queryParam.get("menuid").toString());
        wfActionDTO.setBizKeyName("biz_key");
        wfActionDTO.setYear(userDto.getYear()+"");
        wfActionDTO.setProvince(userDto.getProvince());
        // 流程状态
        // 待办
        if ("1".equals(queryParam.get("flag"))) {
            logger.info("===查询待办Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.TODO.getCode());

           // bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfos(userDto,wfActionDTO);
            logger.info("====查询待办End === " + bizKeys);
        }
        // 已办
        else if ("2".equals(queryParam.get("flag"))) {
            logger.info("===查询已办Begin====");
            // 获取已办
            wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());
           // bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfos(userDto,wfActionDTO);
//            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            // 获取曾经办数据
            //wfActionDTO.setStatus(StatusCodeEnum.ONCE_FINISHED.getCode());
            //List<String> onceBizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
//            if (StringUtils.isEmpty(bizKeys)) {
//                bizKeys = new ArrayList<>();
//            }
            /*if (!StringUtils.isEmpty(onceBizKeys) && onceBizKeys.size() > 0) {
                bizKeys.addAll(onceBizKeys);
            }*/
            logger.info("====查询已办End === " + bizKeys);
        }
        if ("-1".equals(queryParam.get("flag"))) {
            logger.info("===查询被退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());
          //  bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfos(userDto,wfActionDTO);
//            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            logger.info("====查询被退回End === " + bizKeys);
        }
        if("-2".equals(queryParam.get("flag"))){
            logger.info("===查询已退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BACK.getCode());
            //bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfos(userDto,wfActionDTO);
//            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
            logger.info("====查询已退回End === " + bizKeys);
        }
        // 查询合计
//        logger.info("====查询审核数据START === " +  DateUtils.getCurrentTimeStamp());
//        //FinancialAuditVO financialAuditVO = iFinancialAuditDao.queryFinancialAuditDataTotal(queryParam, bizKeys, childrenId);
//        logger.info("====查询审核数据END === " + DateUtils.getCurrentTimeStamp());
        // 查询列表数据
        logger.info("====查询审核数据明细START === " +  DateUtils.getCurrentTimeStamp());
        List<FinancialAuditVO> list = iFinancialAuditDao.queryFinancialAuditPage(paginationDTO, queryParam, bizKeys, childrenId);
        logger.info("====查询审核数据明细END === " +  DateUtils.getCurrentTimeStamp());

        int total = iFinancialAuditDao.queryFinancialAuditTotal(queryParam, bizKeys, childrenId);
        PageDTO<FinancialAuditVO> pageDTO = new PageDTO<>();
        pageDTO.setRows(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void financialAuditPass(UserDTO userDto, FinancialAuditVO financialAuditVO) throws AppRuntimeException {
        //List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyByAgencyIds(financialAuditVO.getAgencyIds());
        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyBizKey(financialAuditVO.getBizKeys());
        List<AgencyVerify>agencyVerifyList=new ArrayList<>();
        List<AgencyVerify>agencyVerifyDoubleList=new ArrayList<>();

        List<AgencyInfo> agencyInfos=agencyInfoDao.queryAgencyInfo(financialAuditVO.getAgencyIds());
        Map<String,String> isPaymentAgency=new HashMap<>();
        for(AgencyInfo agencyInfo:agencyInfos){//将是否是需要生成支付单位的判断加到map中，后续方法取值判断用
            isPaymentAgency.put(agencyInfo.getId(),agencyInfo.getIsPaymentAgency());
        }
        for(AgencyVerify agencyVerify: agencyVerify1s){
            if(agencyVerify.getIsThirteen()>0){
                agencyVerifyDoubleList.add(agencyVerify);
            }else if(agencyVerify.getIsThirteen()<=0){
                agencyVerifyList.add(agencyVerify);
            }
        }
        if(agencyVerifyList.size()>0){
//        if(!StringUtils.isEmpty(agencyVerify1s)) {
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 退回
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerifyList);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());

            // 财政审核通过后，执行工作流节点到下一节点
            for (AgencyVerify agencyVerify1 : agencyVerifyList) {
                // 修改单位表财政审核信息
                agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "通过");
                if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                        financialAuditVO.getParams().contains(SystemDictConstant.FINANCIAL_FLOW_REPORT)) {
                    //判断是否为终审节点
                    agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_TRUE);
                    if("0".equals(isPaymentAgency.get(agencyVerify1.getAgencyId()))){//判断单位是否是实拨单位，实拨单位跳过生成支付直接生成银行数据
                        agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_TRUE);
                    }
                }
//            agencyVerify1.setAuditExplain(financialAuditVO.getMenuname() + "：" + financialAuditVO.getAuditExplain());
            }
            iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

            logger.info("==== 工作流财政审核通过Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO);
            logger.info("==== 工作流财政审核通过完毕End  ===");
//        }
        }
        if(agencyVerifyDoubleList.size()>0){
//        if(!StringUtils.isEmpty(agencyVerify1s)) {
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 退回
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerifyDoubleList);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());

            // 财政审核通过后，执行工作流节点到下一节点
            for (AgencyVerify agencyVerify1 : agencyVerifyDoubleList) {
                // 修改单位表财政审核信息
                agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "通过");
                if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                        financialAuditVO.getParams().contains(SystemDictConstant.FINANCIAL_FLOW_REPORT)) {
                    //判断是否为终审节点
                    agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_TRUE);
                    if("0".equals(isPaymentAgency.get(agencyVerify1.getAgencyId()))){//判断单位是否是实拨单位，实拨单位跳过生成支付直接生成银行数据
                        agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_TRUE);
                    }
                }
//            agencyVerify1.setAuditExplain(financialAuditVO.getMenuname() + "：" + financialAuditVO.getAuditExplain());
            }
            iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

            logger.info("==== 批次工作流财政审核通过Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList1(userDto, wfActionDTO);
            logger.info("==== 批次工作流财政审核通过完毕End  ===");
//        }
        }
    }

    /**
     * 审核岗退回
     * @param userDto
     * @param financialAuditVO
     * @throws AppRuntimeException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void financialAuditReject(UserDTO userDto, FinancialAuditVO financialAuditVO) throws AppRuntimeException {

        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyBizKey(financialAuditVO.getBizKeys());


        if(!StringUtils.isEmpty(agencyVerify1s)) {
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 退回
            wfActionDTO.setActionType(ActionTypeEnum.WF_BACK.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerify1s);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());
            List<String> agencyIds=financialAuditVO.getAgencyIds();
            List<String> backe2agencyIds=new ArrayList<>();//需要退回到单位的agencyId集合
            int  IsThirteen=0;
            // 财政审核退回后，执行工作流节点到上一节点
            for (AgencyVerify agencyVerify1 : agencyVerify1s) {

                // 修改单位表财政审核信息
                agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "退回");
                agencyVerify1.setAuditExplain(financialAuditVO.getMenuname() + "：" + financialAuditVO.getAuditExplain());
                agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_FALSE);
                //根据状态判断数据走向
                if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                        financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT)) {
                    //存在退回到单位信息则
                    agencyVerify1.setIsSalarySubmit(Integer.parseInt(SystemDictConstant.IS_REJECT));
                    if (SystemDictConstant.IS_SUBMIT.equals(agencyVerify1.getIsAuto())||"220723990".equals(userDto.getProvince())||
                            financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT_START) ) {
                        agencyVerify1.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_REJECT));
                    }
                    agencyVerify1.setIsAuto(String.valueOf(SystemDictConstant.IS_FALSE));//修改自动上报状态为非自动上报
                }
                agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_FALSE);
                IsThirteen= agencyVerify1.getIsThirteen();
                //iAgencyVerifyDao.updateFinancialVerifyStatus(agencyVerify1);
                // 调用工作流退回
            }
            if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                    financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT)) {
                //若为带退回到单位标识则，删除上报数据
                personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds,IsThirteen);
                salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmits(userDto.getProvince(), agencyIds,IsThirteen);
                //获取已锁定指标
                List<Map<String,Object>> payLockMap=iPayMentLockDao.selectPayMentLock(agencyIds);
                for(Map<String,Object> map:payLockMap) {
                    //解冻指标
                    commonService.gocpurbudgetThaw(map.get("bgt_id").toString(),map.get("amt").toString(),userDto.getProvince(),userDto.getYear()+"",null);
                }
                //清楚指标锁定表该单位的锁定信息
                iPayMentLockDao.batchPhysicalDeletePayMentLock(agencyIds);
            }
            iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

             for(AgencyVerify agencyVerify :agencyVerify1s){
                 if(agencyVerify.getIsThirteen()<=0){
                     logger.info("==== 工作流财政审核退回Start  ===");
                     iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO);
                     logger.info("==== 工作流财政审核退回完毕End  ===");
                 }else if(agencyVerify.getIsThirteen()>0){
                     logger.info("==== 工作流财政审核退回Start  ===");
                     iSalaryWorkFlowService.doSalaryFlowList1(userDto, wfActionDTO);
                     logger.info("==== 工作流财政审核退回完毕End  ===");
                 }
             }

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void financialAuditRevoke(UserDTO userDto, FinancialAuditVO financialAuditVO) throws AppRuntimeException {
        // 财政审核撤销审核
        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyByAgencyIdsBizkey(financialAuditVO.getAgencyIds(),financialAuditVO.getBizKeys());

        List<AgencyVerify> agencyVerifyList=new ArrayList<>();
        List<AgencyVerify> agencyVerifyDoubleList=new ArrayList<>();
        for(AgencyVerify agencyVerify:agencyVerify1s){
            if(agencyVerify.getIsThirteen()>0){
                agencyVerifyDoubleList.add(agencyVerify);
            }else if(agencyVerify.getIsThirteen()<=0){
                agencyVerifyList.add(agencyVerify);
            }
            agencyVerify.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            agencyVerify.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "撤销审核");
            agencyVerify.setIsConfirmSubmit(SystemDictConstant.IS_FALSE);
            agencyVerify.setIsPayDataCreated(SystemDictConstant.IS_FALSE);
        }
        if(agencyVerifyList.size()>0){
            // 撤销流程
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 审核
            wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerifyList);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());

            logger.info("==== 财政撤销审核每月工资Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO);
            logger.info("==== 财政撤销审核每月工资Start  ===");
        }
        if(agencyVerifyDoubleList.size()>0){
            // 撤销流程
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 审核
            wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerifyDoubleList);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());
            // 财政确认后，执行工作流节点到下一节点
            logger.info("==== 财政撤销审核多批次Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList1(userDto, wfActionDTO);
            logger.info("==== 财政撤销审核多批次end  ===");
        }
        iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

    }
}
